package com.bnz.search.util;


import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch.core.BulkRequest;
import co.elastic.clients.elasticsearch.core.BulkResponse;
import co.elastic.clients.elasticsearch.indices.CreateIndexRequest;
import co.elastic.clients.elasticsearch.indices.CreateIndexResponse;
import co.elastic.clients.util.ObjectBuilder;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bnz.search.dao.ItemDao;
import com.bnz.search.entity.ItemEntity;
import org.elasticsearch.action.DocWriteRequest;

import org.elasticsearch.action.index.IndexRequest;

import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;

// import org.elasticsearch.common.settings.Settings;
// import org.elasticsearch.common.xcontent.XContentBuilder;
// import org.elasticsearch.common.xcontent.XContentFactory;
// import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.xcontent.XContentBuilder;
import org.elasticsearch.xcontent.XContentFactory;
import org.elasticsearch.xcontent.XContentType;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.query.Criteria;
import org.springframework.data.elasticsearch.core.query.CriteriaQuery;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;


@SpringBootTest
public class ESUtil {
    /**
     * 将数据库中的数据导入到索引库中
     */
    @Autowired
    private ItemDao itemDao;
    @Autowired
    private ElasticsearchRestTemplate restTemplate;

    //删除一个索引，，用于操作索引转台
    @Test
    public void test01(){
        Long id = 1588730097213054977L;
        // Query query = new CriteriaQuery(Criteria.where("goodsId").is(id));
        CriteriaQuery query = CriteriaQuery.builder(Criteria.where("goodsId").is(id)).build();

        restTemplate.delete(query,ItemEntity.class);
    }

     /* 使用ElasticsearchRestTemplate添加数据到索引库
     */
    @Test
    public void importData() {
        //询经审核通过后的商品
        List<ItemEntity> status = itemDao.selectList(new QueryWrapper<ItemEntity>().eq("status", 1));
        System.out.println("status = " + status);
        for (ItemEntity item : status) {
            //得到规
            String spec = item.getSpec();
            //规格值转换为map对象
            Map map = JSON.parseObject(spec, Map.class);
            //map直接赋值给specMap
            item.setSpecMap(map);
        }
        //将上面的集合数据导入到索引库中
        restTemplate.save(status);
        System.out.println("status = " + status);
        System.out.println("保存成功！");
    }
    //3. 创建索引库使用JSON串的形式并同时指定分词器,
    // 用于ES7.6.2这种稍低的版本
    @Test
    public void createIndex2() throws IOException {
        // CreateIndexRequest request = new CreateIndexRequest("item2");
        // String source =  "{\n" +
        // 		"  \"properties\": {\n" +
        // 		"    \"title\": {\n" +
        // 		"      \"type\": \"text\",\n" +
        // 		"      \"analyzer\": \"ik_smart\"\n" +
        // 		"    },\n" +
        // 		"    \"price\": {\n" +
        // 		"      \"type\": \"float\"\n" +
        // 		"    },\n" +
        // 		"    \"brand\": {\n" +
        // 		"      \"type\": \"keyword\"\n" +
        // 		"    },\n" +
        // 		"    \"category\": {\n" +
        // 		"      \"type\": \"keyword\"\n" +
        // 		"    }\n" +
        // 		"  }\n" +
        // 		"}";
        // request.mapping(source, XContentType.JSON);
        // client.indices().create(request, RequestOptions.DEFAULT);
    }
    //3. 创建索引库 [方法三：使用JSON串],并同时指定分词器,适用于ES7.6.2这种稍低的版本
    @Test
    public void createIndex3() throws IOException {
        // CreateIndexRequest request = new CreateIndexRequest("item3");
        // Map<String, Object> source = new HashMap<>();
        // HashMap<String, Object> contentMap = new HashMap<>();
        // source.put("properties",contentMap);
        // //3.2 定义标题map
        // Map<String,Object> titleMap = new HashMap<>();
        // titleMap.put("type","text");
        // titleMap.put("analyzer","ik_smart");
        // contentMap.put("title",titleMap);
        // //3.3 定义价格的map
        // Map<String,Object> priceMap = new HashMap<>();
        // priceMap.put("type","float");
        // contentMap.put("price",priceMap);
        // //3.4 定义分类的map
        // Map<String,Object> categoryMap = new HashMap<>();
        // categoryMap.put("type","keyword");
        // contentMap.put("category",categoryMap);
        // //3.5 定义品牌的map
        // Map<String,Object> brandMap = new HashMap<>();
        // brandMap.put("type","keyword");
        // contentMap.put("brand",brandMap);
        //
        // request.mapping(source);
        // client.indices().create(request, RequestOptions.DEFAULT);
    }


    /**
     * 3. 使用RestHighLevelClient API添加数据到索引库中 (ES7.6.2 当然也可以使用ElasticsearchRestTemplate方式添加)
     * @throws IOException
     */
    @Test
    public void importData2() throws IOException {
        //3.1 查询经审核通过后的商品
        List<ItemEntity> itemEntities = itemDao.selectList(new QueryWrapper<ItemEntity>().eq("status", "1"));
        //3.2 处理上面的数据
        for (ItemEntity item : itemEntities) {
            //3.2.1 得到规格值
            String spec = item.getSpec();
            //3.2.2 将规格值转换为map对象
            Map map = JSON.parseObject(spec, Map.class);
            //3.2.3 将此map直接赋值给specMap
            item.setSpecMap(map);
        }
        //3.3 构造bulkRequest对象
        // BulkRequest bulkRequest = new BulkRequest("item");
        // //3.4 将数据库中的数据添加到list集合中
        // List<DocWriteRequest<?>> list = new ArrayList<>();
        // for (ItemEntity entity : itemEntities) {
        // 	String s = JSON.toJSONString(entity);
        // 	Map map = JSON.parseObject(s, Map.class);
        // 	list.add(new IndexRequest("item").id(entity.getId() + "").source(map));
        // }
        // //3.5 将批量请求的集合添加到bulkRequest对象中
        // bulkRequest.add(list);
        // // 3.6 使用客户端工具进行批量添加
        // client.bulk(bulkRequest,RequestOptions.DEFAULT);

    }


}
